package com.maniu.douyinclip;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class MainActivity extends AppCompatActivity {
    VideoView videoView;
    SeekBar musicSeekBar;
    SeekBar voiceSeekBar;
    int musicVolume = 0;
    int voiceVolume = 0;
    Runnable runnable;
    int duration = 0;
    private String aacPath;
    private String videoPath;
    private String outputPath;
    private HandlerThread mHandlerThread;
    private Handler mWorkHandler;
    private String videoPCMPath;
    private String audioPCMPath;
    private String mixPCMPath;
    private String mixWavPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        videoView = findViewById(R.id.videoView);
        musicSeekBar = findViewById(R.id.musicSeekBar);
        voiceSeekBar = findViewById(R.id.voiceSeekBar);
        musicSeekBar.setMax(100);
        voiceSeekBar.setMax(100);
        musicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                musicVolume = progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        voiceSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                voiceVolume = progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        initFilePath();
        if (mHandlerThread == null) {
            mHandlerThread = new HandlerThread("copyFileHandlerThread");
        }
        mHandlerThread.start();
        mWorkHandler = new Handler(mHandlerThread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                if (msg.what == 1) {
                    try {
                        copyAssets("music.mp3", aacPath);
                        copyAssets("input.mp4", videoPath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            startPlay(videoPath);
                        }
                    });

                } else if (msg.what == 2) {
                    try {
                        MusicProcess.mixAudioTrack(videoPath, aacPath, outputPath,
                                (int) (60 * 1000 * 1000),//60秒
                                (int) (100 * 1000 * 1000),// 100秒
                                voiceVolume,
                                musicVolume,
                                videoPCMPath,
                                audioPCMPath,
                                mixPCMPath,
                                mixWavPath
                        );
                        Log.d("douyin", "finish task >>>>>>>>>>>>>>>>>>>>>>>>>>");
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "制作完成", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        });
    }

    private void initFilePath() {
        ///storage/emulated/0/Android/data/包名/files/music。mp3
        aacPath = new File(getExternalFilesDir(null), "music.mp3").getAbsolutePath();
        videoPath = new File(getExternalFilesDir(null), "input.mp4").getAbsolutePath();
        //剪辑好的视频输出放哪里
        outputPath = new File(getExternalFilesDir(null), "output.mp4").getAbsolutePath();
        videoPCMPath = new File(getExternalFilesDir(null), "video.pcm").getAbsolutePath();
        audioPCMPath = new File(getExternalFilesDir(null), "audio.pcm").getAbsolutePath();
        mixPCMPath = new File(getExternalFilesDir(null), "mix.pcm").getAbsolutePath();
        mixWavPath = new File(getExternalFilesDir(null), "mix.wav").getAbsolutePath();
    }

    private void copyFile() {
        File videoFile = new File(videoPath);
        if (!videoFile.exists()) {
            Message msg = Message.obtain();
            msg.what = 1; //消息的标识
            // b. 通过Handler发送消息到其绑定的消息队列
            mWorkHandler.sendMessage(msg);
        } else {
            startPlay(videoPath);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        copyFile();
    }

    private void startPlay(String path) {
        Log.d("startPlay", "path: " + path);
        Log.d("startPlay", "current thread:" + Thread.currentThread().getName());
        ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
        layoutParams.height = 675;
        layoutParams.width = 1285;
        videoView.setLayoutParams(layoutParams);
        videoView.setVideoPath(path);

        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                duration = mp.getDuration() / 1000;
                mp.setLooping(true);
            }
        });
        videoView.start();
    }

    private void copyAssets(String assetsName, String path) throws IOException {
        AssetFileDescriptor assetFileDescriptor = getAssets().openFd(assetsName);
        FileChannel from = new FileInputStream(assetFileDescriptor.getFileDescriptor()).getChannel();
        FileChannel to = new FileOutputStream(path).getChannel();
        from.transferTo(assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength(), to);
    }

    public void music(View view) {
//        大片制作的时候
//         剪辑的起始的时间  终止时间， 视频调整后的音乐大小 ，原生大小
        Message msg = Message.obtain();
        msg.what = 2; //消息的标识
        // b. 通过Handler发送消息到其绑定的消息队列
        mWorkHandler.sendMessage(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //释放资源
        mHandlerThread.quit();
    }
}

